package com.learning.servlet2x.cookie;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ClassName: LoginCookieServlet
 * Description: 永久登录 登录的servlet
 * 1、访问JSP : http://localhost:8080/cookie/loginCookie.jsp
 * Date: 2018/6/24 13:03 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class LoginCookieServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    /**
     * 密钥, 可以放配置文件
     */
    private static final String KEY = ":https://sam-blog.gitee.io/";


    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    /**
     * post方法访问，处理永久登录
     */
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        String action = request.getParameter("action");

        if ("login".equals(action)) {

            String account = request.getParameter("account");
            int timeout = new Integer(request.getParameter("timeout"));

            // 把帐号连同密钥使用MD5后加密后保存, 这边加密略
            String ssid = account + KEY;

            // 把帐号保存到Cookie中 并控制有效期
            // 中文需要编码
            Cookie accountCookie = new Cookie("account", account);
            accountCookie.setMaxAge(timeout);

            // 把加密结果保存到Cookie中 并控制有效期
            Cookie ssidCookie = new Cookie("ssid", ssid);
            ssidCookie.setMaxAge(timeout);
            // 账户Cookie
            response.addCookie(accountCookie);
            // 加密后账户的Cookie
            response.addCookie(ssidCookie);

            System.out.println(accountCookie.getName() + "++++++++" + accountCookie.getValue());
            System.out.println(ssidCookie.getName() + "+++++++" + ssidCookie.getValue());

            // 重定向到校验servlet
            // 使用两个request,这样访问到校验的request就带有了本次response写入的cookie。
            response.sendRedirect(this.getServletContext().getContextPath() + "/checkCookieServlet");
            return;
        }
    }
}
